#include <stdio.h>
#include <stdlib.h>
#include "uv.h"

int demo_main(int argc, char** argv)
{
    return 0;
}

int t1_main(int argc, char** argv)
{
    char *version = NULL;
    version = (char *)uv_version_string();
    printf("version: %s\n", version);
    uv_loop_t *loop = uv_loop_new();
    printf("Now quitting.\n");
    uv_run(loop, UV_RUN_DEFAULT);
    return 0;
}

int t2_main(int argc, char** argv)
{
    uv_loop_t *loop = malloc(sizeof(uv_loop_t));
    uv_loop_init(loop);

    printf("Now quitting.\n");
    uv_run(loop, UV_RUN_DEFAULT);

    uv_loop_close(loop);
    free(loop);
    return 0;
}

int64_t counter = 0;

void wait_for_a_while(uv_idle_t* handle)
{
    counter++;
    
    printf("counter: %ld\n", counter);

    if (counter >= 10e6)
    {
        uv_idle_stop(handle);
    }
}

/**
 * brief: idle handle 
 */
int idle_main(int argc, char** argv)
{
    uv_idle_t idler; 

    uv_idle_init(uv_default_loop(), &idler);
    uv_idle_start(&idler, wait_for_a_while);

    printf("Idling...\n");
    uv_run(uv_default_loop(), UV_RUN_DEFAULT);

    uv_loop_close(uv_default_loop());
    return 0;
}

uv_loop_t *loop;
uv_timer_t gc_req;
uv_timer_t fake_job_req;

void gc(uv_timer_t* handle)
{
    printf("[%s %d]\n", __FUNCTION__, __LINE__);
}

void fake_job(uv_timer_t* handle)
{
    printf("[%s %d]\n", __FUNCTION__, __LINE__);
}

int timer_main(int argc, char** argv)
{
    loop = uv_default_loop();

    uv_timer_init(loop, &gc_req);
    uv_unref((uv_handle_t*) &gc_req);
    uv_timer_start(&gc_req, gc, 0, 2000);

    uv_timer_init(loop, &fake_job_req);
    uv_timer_start(&fake_job_req, fake_job, 9000, 0);
    return uv_run(loop, UV_RUN_DEFAULT);
}

int main(int argc, char** argv)
{
    /* t1_main(argc, argv); */
    /* t2_main(argc, argv); */
    /* idle_main(argc, argv); */
    timer_main(argc, argv);
    return 0;
}

